// pages/index/add_event/add_event.js
const db = wx.cloud.database()
const cloudEvenList = db.collection("eventList")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    color: 'cyan',
    tabCur: 0,
    name: null,
    tabList: ["正/倒数日", "生日", "纪念日"],
    date: '2020-01-01',
    createDate: null,
    remark: null,
    _id: null
  },

  tabSelect(e) {
    this.setData({
      tabCur: e.currentTarget.dataset.id,
    })
  },

  nameChange(e) {
    this.setData({
      name: e.detail.value
    })
  },

  dateChange(e) {
    this.setData({
      date: e.detail.value
    })

    console.log(this.data.date)
  },

  textareaInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  submitEvent() {
    if (this.data.name === null) {
      wx.showModal({
        title: '失败',
        content: '请填写事件名',
      })
      return;
    }

    this.setData({
      createDate: new Date().getTime()
    })
    console.log(this.data.createDate)

   // cloudEvenList.add({
    //   data: event
    // }).then(res => {
    //   console.log(res)
    // })
    // 调用云函数
    wx.cloud.callFunction({
      name: 'add',
      data: {
        _openid: wx.getStorageSync('openid'),
        name: this.data.name,
        date: this.data.date,
        createDate: this.data.createDate,
        remark: this.data.remark
      },
      success: res => {
        this.setData({
          _id: res.result._id
        })
        console.log('add调用成功: ', res.result._id)

        let event = {
          '_id': this.data._id,
          '_openid': wx.getStorageSync('openid'),
          'name': this.data.name,
          'date': this.data.date,
          'createDate': this.data.createDate,
          'remark': this.data.remark
        }
        let eventList = wx.getStorageSync('eventList')
        eventList.unshift(event)
        wx.setStorageSync('eventList', eventList)

        const event_json = JSON.stringify(event);
        wx.redirectTo({
          url: '../event_detail/event_detail?event_json=' + event_json,
        })  

      },
      fail: err => {
        console.error('add调用失败', err)
      }
    })





  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      color: wx.getStorageSync('color')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})